package com.sec.etech.sys.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import org.openbpm.base.core.util.StringUtil;
import org.openbpm.form.util.JdbcTemplateUtil;
import org.openbpm.sys.api.model.dto.DataDictDTO;
import org.openbpm.sys.core.model.DataDict;
import org.openbpm.sys.service.impl.DataDictServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service("etechDictService")
public class EtechDictServiceImpl extends DataDictServiceImpl {

    private JdbcTemplate jdbcTemplate;

    private JdbcTemplate getJdbcTemplate(){
        if(jdbcTemplate==null){
            jdbcTemplate = JdbcTemplateUtil.getJdbcTemplate("dataSourceDefault");
        }
        return  jdbcTemplate;
    }

    @Cacheable("dictNode")
    public List<DataDictDTO> getDictNodeList(String dictKey, Boolean hasRoot){
        return super.getDictNodeList(dictKey, hasRoot);
    }

    @Cacheable("dictNode2")
    public List<DataDictDTO> getDictNodeList4grid(String dictKey){
        if(dictKey==null){
            return null;
        }
        if(dictKey.endsWith("_ext")){
            return super.getDictNodeList(dictKey, false);
        }
        String sql = getDictSql(dictKey);
        if(StringUtil.isEmpty(sql)){
            return super.getDictNodeList(dictKey, false);
        }
        List<DataDictDTO> nodeList = null;
        try {
            sql = parseSqlWithAll(sql);
            if (StringUtil.isNotEmpty(sql)) {
                nodeList = getDictNodeListFromSQL(sql);
            }
        } catch (Exception e) {
            nodeList = null;
        }

        // 取消自动注入 0 值筛选，由 (空值) 筛选替代
        if (CollectionUtil.isNotEmpty(nodeList)) {
            // boolean withZero = false;
            // for(DataDictDTO item: nodeList){
            //     if("0".equals(item.getKey())){
            //         withZero = true;
            //         break;
            //     }
            // }
            // if(!withZero){
            //     DataDictDTO item0 = new DataDictDTO();
            //     item0.setKey("0");
            //     item0.setName(" ");
            //     nodeList.add(item0);
            // }
            return nodeList;
        }

        // 2021年9月13日 范彦青
        // 数据字典扩展 key 如果是 0 ，将其 name 转为空而非使用 0
        List<DataDictDTO> dictNodeList = super.getDictNodeList(dictKey, false);
        for (DataDictDTO item : dictNodeList) {
            if ("0".equalsIgnoreCase(item.getKey())) {
                item.setName(" ");
                break;
            }
        }

        return dictNodeList;
    }

    @CacheEvict("dictNode2")
    public List<DataDictDTO>  deleteDictCache(String dictKey){
            return new ArrayList<>();
    }

    private String parseSqlWithAll(String sql){
        int n1,n2;
        // 1. end with  where active = 1
        //where active >0
        if(sql.toLowerCase().endsWith("where active >0") || sql.toLowerCase().endsWith("where active>0") || sql.toLowerCase().endsWith("where active = 1") || sql.toLowerCase().endsWith("where active = 1;")){
            sql = sql.substring(0, sql.lastIndexOf("where")-1);
            return sql;
        }
        // 2. end with  and active = 1
        if(sql.toLowerCase().endsWith("and active = 1") || sql.toLowerCase().endsWith("and active = 1;")){
            sql = sql.substring(0, sql.lastIndexOf("and")-1);
            return sql;
        }
        // 3. where active=1 and
        n1 = sql.toLowerCase().lastIndexOf("where active=1 and");
        if(n1>0){
            sql = sql.substring(0, n1+5) + sql.substring(n1+18);
            return sql;
        }
        return  null;
    }

    private String getDictSql(String dictKey){
        String sql = null;
        List<Map<String,Object>> list = getJdbcTemplate().queryForList("select cust_data_ as sqlstr " +
                " from sys_data_dict " +
                " where dict_type_='dict' and source_='sql' and key_='"+dictKey+"'");
        if(list!=null && !list.isEmpty()){
            sql = MapUtil.getStr(list.get(0), "sqlstr");
        }
        return sql;
    }


    @Transactional(readOnly = true)
    List<DataDictDTO> getDictNodeListFromSQL(String sql) {
        List<DataDictDTO> nodeList = new ArrayList<>();

            JdbcTemplate jdbcTemplate1 = getJdbcTemplate();
            List<Map<String, Object>> rowData = jdbcTemplate1.queryForList(sql);

            List remainKeys = Arrays.asList(new String[]{"id","key_","value_","name_","label_","delete_flag_"});
            int i = 0;
            for (Map<String, Object> map : rowData) {
                String key = String.valueOf(map.get("key_"));
                if (StringUtil.isEmpty(key)) {
                    key = String.valueOf(map.get("value_"));
                }
                if (StringUtil.isEmpty(key)) {
                    continue;
                }
                String name = String.valueOf(map.get("name_"));
                if (StringUtil.isEmpty(name)) {
                    name = String.valueOf(map.get("label_"));
                }
                if (StringUtil.isEmpty(name) || "null".equalsIgnoreCase(name)) {
                    name = key;
                }

                // check delete/enable/active
                String deleteFlag = "0";
                if(map.containsKey("delete_flag_")){
                    deleteFlag = String.valueOf(map.get("delete_flag_"));
                }else if(map.containsKey("active")){
                    if("0".equals(String.valueOf(map.get("active")))){
                        deleteFlag = "1";
                    }
                }else if(map.containsKey("enable")){
                    if("0".equals(String.valueOf(map.get("enable")))){
                        deleteFlag = "1";
                    }
                }
                i++;
                DataDictDTO node = new DataDictDTO();
                node.setDictType(DataDict.TYPE_NODE);
                node.setKey(key);
                node.setName(name);
                node.setSn(i);
                node.setDeleteFlag(deleteFlag);
                // 返回其他字段
                if(map.keySet().size()>2){
                    JSONObject extData = new JSONObject();
                    for(String key2: map.keySet()){
                        if(!remainKeys.contains(key2)){
                            extData.put(key2, map.get(key2));
                        }
                    }
                    node.setExtData(extData);
                }
                nodeList.add(node);
            }

        return nodeList;
    }
}
